<template>
  <div>
    <div v-if="step===1">
      <div class="big-t">
        选择/创建试卷
      </div><el-card>
        <div style="padding-bottom: 10px">
          <el-radio v-model="checkType" :label="1">
            选择已有试卷创建考试
          </el-radio>
        </div>
        <div v-if="checkType===1">
          <tmpl-list :select-mode="true" @select="handleBack" />
        </div>
      </el-card> <el-card style="margin-top: 20px">
        <el-radio v-model="checkType" :label="2">
          新建试卷并创建考试
        </el-radio>
        <div v-if="checkType===2" style="padding-top: 20px">
          <tmpl-pre-create @confirm="handleCreate" />
        </div>
      </el-card>
    </div>
    <div v-if="step===2" style="margin-left: -20px; margin-right: -20px; padding-top: 20px">
      <join1-form :title="createForm.title" :cat-id="createForm.catId" :join-type="createForm.joinType" @back="handleBack" />
    </div>
    <div v-if="step===3">
      <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="18">
            <div class="big-t">
              考试配置
            </div>
            <el-card>
              <el-tabs v-model="tabActive" :stretch="true" tab-position="left" class="body-h">
                <el-tab-pane label="基本设置" name="base">
                  <el-row :gutter="50" type="flex" style="flex-wrap:wrap; flex-direction: row">
                    <el-col :span="24">
                      <el-form-item label="考试名称" prop="title">
                        <el-input v-model="postForm.title" size="small" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="考试时间" prop="dateRange">
                        <el-date-picker v-model="postForm.dateRange" size="small" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="及格分" prop="qualifyScore">
                        <el-input-number v-model="postForm.qualifyScore" :max="tmplData.totalScore" :min="0" :precision="1" size="small" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="考试时长" prop="totalTime">
                        <el-input-number v-model="postForm.totalTime" :min="5" :max="999" size="small" />
                        <tool-tip msg="单位：分钟" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="限考次数" prop="chance">
                        <el-input-number v-model="postForm.chance" :min="0" size="small" />
                        <tool-tip msg="限制每个考生有几次考试机会，0为不限制" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="最低交卷时长">
                        <el-input-number v-model="postForm.handMin" :min="0" size="small" />
                        <tool-tip msg="最低答题分钟数，未达到不允许交卷，0为不开启" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="允许迟到时长">
                        <el-input-number v-model="postForm.lateMax" :min="0" size="small" />
                        <tool-tip msg="允许迟到的分钟数，注意：某段时间都可以考试的长期考试请设置为0" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="是否是AI">
                        <el-switch v-model="postForm.isAi"></el-switch>
                        <tool-tip msg="是否是AI" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="考前注意事项">
                        <tinymce ref="editor" v-model="postForm.content" :height="250" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-tab-pane>
                <el-tab-pane label="权限配置">
                  <div>
                    <el-radio-group v-model="postForm.openType" size="small">
                      <el-radio :label="1">
                        完全公开
                      </el-radio>
                      <el-radio :label="3">
                        部分学员
                      </el-radio>
                      <el-radio :label="9">
                        口令密码
                      </el-radio>
                      <el-radio :label="99">
                        私密考试
                      </el-radio>
                    </el-radio-group>
                    <div style="padding-top: 20px">
                      <div v-if="postForm.openType===1">
                        <el-alert title="开放的，任何人都可以参与学习！" type="warning" />
                      </div>
                      <div v-if="postForm.openType===3">
                        <user-range :users.sync="postForm.userList" :departs.sync="postForm.deptCodes" :groups.sync="postForm.groupIds" />
                      </div>
                      <div v-if="postForm.openType===9">
                        <el-form-item label="考试密码" prop="password">
                          <el-input v-model="postForm.password" size="small" placeholder="输入考试密码" />
                        </el-form-item>
                      </div>
                      <div v-if="postForm.openType===99">
                        <el-alert title="私密考试用于课程关联考试、报名关联考试；被关联后，不允许修改为其他权限！" type="error" />
                      </div>
                    </div>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="防作弊配置">
                  <el-form-item label="学员答题设备设置" label-width="240px">
                    <el-radio-group v-model="postForm.answerDevice">
                      <el-radio :label="0" :disabled="postForm.examType==='2'">
                        可使用电脑或手机
                      </el-radio>
                      <el-radio :label="1">
                        仅电脑
                      </el-radio>
                      <el-radio :label="2" :disabled="postForm.examType==='2'">
                        仅手机
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="人脸认证进入考试" label-width="240px">
                    <el-switch v-model="postForm.faceOn" active-color="#13ce66" inactive-color="#ff4949" />  开启后，需要人脸认证通过才可以进入考试
                  </el-form-item>
                  <el-form-item label="摄像头定时抓拍（仅PC）" label-width="240px">
                    <el-switch v-model="postForm.camOn" active-color="#13ce66" inactive-color="#ff4949" />
                    <span v-if="postForm.camOn"> 学员开始答题后，每  <el-input-number v-model="postForm.camInterval" :min="1" :max="30" label="秒数" size="mini" />  分钟抓拍一张学员答题照片  </span>
                  </el-form-item>
                  <el-form-item v-if="postForm.camOn" label="考试过程定时人脸识别（仅PC）" label-width="240px">
                    <el-switch v-model="postForm.faceCheck" active-color="#13ce66" inactive-color="#ff4949" /> 对抓拍图片进行人脸识别，如果连续识别失败超过
                    <el-input-number v-model="postForm.faceChance" :min="0" :max="9999" label="次数" size="mini" /> 次就强制交卷
                  </el-form-item>
                  <el-form-item label="切屏后强制交卷" label-width="240px">
                    <el-switch v-model="postForm.leaveOn" active-color="#13ce66" inactive-color="#ff4949" />
                    <span v-if="postForm.leaveOn">  学员切换页面超过  <el-input-number v-model="postForm.leaveCount" :min="1" :max="999" label="秒数" size="mini" /> 次后将被强制交卷，切换到其他页面  <el-input-number v-model="postForm.leaveCheck" :min="5" :max="999" label="秒数" size="mini" /> 秒后即判定为切屏 </span>
                  </el-form-item>
                  <el-form-item label="无操作强制交卷" label-width="240px">
                    <el-switch v-model="postForm.actionOn" active-color="#13ce66" inactive-color="#ff4949" />
                    <span v-if="postForm.actionOn">  答题时超过  <el-input-number v-model="postForm.actionInterval" :min="1" :max="999" label="秒数" size="mini" />  秒学员没有任何交互则强制交卷  </span>
                  </el-form-item>
                  <el-form-item label="开启考试水印" label-width="240px">
                    <div style="display: flex; align-items: center">
                      <el-switch v-model="postForm.waterMark" active-color="#13ce66" inactive-color="#ff4949" /> <tool-tip msg="在答题界面显示考生信息，防止考生拍照泄露试题" />
                    </div>
                  </el-form-item>
                  <el-form-item label="禁止查看错题" label-width="240px">
                    <el-switch v-model="postForm.hideBook" active-color="#13ce66" inactive-color="#ff4949" /> 允许考试多次的考试，应开启此项
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="答题模式">
                  <el-form-item label="答题模式">
                    <el-radio-group v-model="postForm.answerMode" size="small">
                      <el-radio :label="1">
                        逐题模式
                      </el-radio>
                      <el-radio :label="2">
                        整卷模式
                      </el-radio>
                    </el-radio-group>
                    <el-alert v-if="postForm.answerMode===1" title="每次只显示一题，可通过答题卡或上一题下一期切换试题" type="success" />
                    <el-alert v-if="postForm.answerMode===2" title="显示整张试卷，列出所有题目" type="success" />
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="监考配置" style="padding-left: 10px">
                  <watch-settings v-model="postForm.watchRule" />
                </el-tab-pane>
                <el-tab-pane label="阅卷配置" style="padding-left: 10px">
                  <review-settings v-model="postForm.reviewRule" :require-review="tmplData.review" :tmpl-id="postForm.tmplId" :end-time="endTime" :join-type="tmplData.joinType" />
                </el-tab-pane>
                <el-tab-pane label="考试结果展示">
                  <el-form-item label="考试结果显示">
                    <el-radio-group v-model="postForm.resultType" size="small">
                      <el-radio :label="1">
                        仅显示感谢文字
                      </el-radio>
                      <el-radio :label="2">
                        显示感谢文字+成绩
                      </el-radio>
                      <el-radio :label="3">
                        显示试卷明细
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item v-if="postForm.resultType!==3" label="考后感谢文字">
                    <el-input v-model="postForm.thanks" type="textarea" maxlength="2000" show-word-limit />
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="积分规则">
                  <points-rule v-model="postForm.pointsRules" />
                </el-tab-pane>
              </el-tabs>
            </el-card>
          </el-col>
          <el-col :span="6">
            <div class="big-t">
              试卷信息
            </div>
            <el-card style="font-size: 14px; line-height: 28px">
              <div>
                试卷标题：<el-link :href="`/admin/tmpl/preview/${tmplData.id}`" type="primary" target="_blank">
                  {{ tmplData.title }}
                </el-link>
              </div>
              <div>
                试卷总分：{{ tmplData.totalScore }}
              </div>
              <div>
                试题数量： {{ tmplData.quCount }}
              </div>
              <div>
                组卷方式： {{ tmplData.joinType_dictText }}
              </div>
              <div>
                人工批阅： <span v-if="tmplData.review" style="color: #ff3333">是</span> <span v-else>否</span>
              </div>
              <div>
                出卷人员：{{ tmplData.createBy_dictText }}
              </div>
              <div>
                创建时间：{{ tmplData.createTime }}
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-button type="primary" style="margin-top: 20px" @click="nextStep">
          保存
        </el-button>
      </el-form>
    </div>
  </div>
</template>
<script>
import { fetchDetail, saveData } from '@/api/exam/exam'
import TmplPreCreate from '@/views/admin/tmpl/components/components/TmplPreCreate'
import Join1Form from '@/views/admin/tmpl/components/Join1Form'
import TmplList from '@/views/admin/tmpl'
import { apiFindSimple } from '@/api/tmpl/tmpl'
import { isDateRange } from '@/utils/validate'
import { mapGetters } from 'vuex'
import PointsRule from '@/views/admin/exam/exam/components/PointsRule.vue'

import moment from 'moment'
import ReviewSettings from '@/views/admin/exam/exam/components/ReviewSettings.vue'
import WatchSettings from '@/views/admin/exam/exam/components/WatchSettings.vue'

export default {
  name: 'ExamAdd',
  components: { WatchSettings, ReviewSettings, PointsRule, TmplList, Join1Form, TmplPreCreate },
  data() {
    return {

      isDemo: this.$demo,
      step: 1,
      checkType: 1,

      tmplData: {

      },

      createForm: {
        data: {
          totalScore: 0
        },
        title: null,
        joinType: 'choose',
        catId: null
      },

      // 表单
      postForm: {
        scoreType: 2,
        stopType: 1,
        examType: '1',
        title: '',
        content: '',
        answerDevice: 0,
        password: '',
        tmplId: '',
        departIds: [],
        groupIds: [],
        chance: 1,
        isAi: false,
        totalTime: 30,
        camInterval: 5,
        actionInterval: 300,
        leaveCount: 5,
        leaveCheck: 5,
        capture: 0,
        openType: 1,
        points: 0,
        price: 0,
        isCapture: true,
        resultType: 2,
        thanks: '感谢您的作答！',
        personList: [],
        camOn: false,
        leaveOn: false,
        actionOn: false,
        faceOn: false,
        faceCheck: false,
        faceInterval: 0,
        faceChance: 5,
        dateRange: ['', ''],
        qualifyScore: 0,
        startTime: '',
        endTime: '',
        waterMark: false,
        hideBook: true,
        pointsRules: [],
        certRules: [],
        answerMode: 1,
        reviewRule: {},
        watchRule: {}
      },
      rules: {
        title: [
          { required: true, message: '考试名称不能为空！' }
        ],
        price: [
          { required: true, message: '考试价格不能为空！' }
        ],
        open: [
          { required: true, message: '考试权限不能为空！' }
        ],

        qualifyScore: [
          { required: true, message: '及格分不能为空！' }
        ],

        totalTime: [
          { required: true, message: '考试时长不能为空！' }
        ],

        dateRange: [
          { required: true, validator: isDateRange }
        ],

        password: [
          { required: true, message: '考试口令不能为空！' }
        ],
        chance: [
          { required: true, message: '考试次数不能为空，0为不限制！' }
        ],
        examType: [
          { required: true, message: '考试类型必须选择' }
        ]
      },
      tabActive: 'base'
    }
  },

  computed: {
    ...mapGetters([
      'siteData'
    ]),
    endTime() {
      if (this.postForm.endTime) {
        return moment(this.postForm.endTime).toDate()
      }
      return null
    }
  },
  created() {
    // 选定创建试卷
    const tmplId = this.$route.params.tmplId
    if (tmplId !== undefined && tmplId !== '0') {
      this.handleBack(tmplId)
      return
    }

    const id = this.$route.params.id
    if (id !== undefined) {
      this.fetchData(id)
    } else {
      this.postForm.openType = 1
      this.postForm.joinType = 'choose'
    }
  },
  methods: {

    nextStep() {
      // 时间段覆盖
      this.postForm.startTime = this.postForm.dateRange[0]
      this.postForm.endTime = this.postForm.dateRange[1]

      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          this.tabActive = 'base'
          return
        }
        this.$confirm('确实要提交保存吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitForm()
        })
      })
    },

    fetchData(id) {
      fetchDetail(id).then(res => {
        const data = res.data
        this.postForm = data
        // 起始时间
        if (data.startTime && data.endTime) {
          this.$set(this.postForm, 'dateRange', [data.startTime, data.endTime])
        }
        this.handleBack(this.postForm.tmplId)
      })
    },

    submitForm() {
      console.error('isAi --->：',this.postForm)
      saveData(this.postForm).then(() => {
        this.$notify({
          title: '成功',
          message: '考试保存成功！',
          type: 'success',
          duration: 2000
        })

        // 清理缓存
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.push({ name: 'ExamList' })
      })
    },

    handleCreate(data) {
      this.createForm = data
      this.step = 2
    },

    handleBack(id) {
      this.step = 3
      this.postForm.tmplId = id
      apiFindSimple(id).then(res => {
        this.tmplData = res.data
        if (!this.postForm.title) {
          this.postForm.title = res.data.title + ' - 考试'
        }

        if (!this.postForm.qualifyScore) {
          this.postForm.qualifyScore = res.data.totalScore * 0.6
        }
      })
    },

    switchType(type) {
      this.postForm.examType = type
    }

  }
}
</script>
<style scoped>

  .type-box{
    display: flex;
    justify-content: space-between;
    padding-bottom: 20px;
  }

  .type-item{
    width: 49%;
    color: #fff;
    line-height: 26px;
    cursor: pointer;
    background-size: 100%;
    padding: 3px;
  }

  .type-item .check{
    display: none;
    font-size: 30px;
  }

  .type-normal{
    background: #0a84ff url("~@/assets/images/dash-ring.png") no-repeat;
  }

  .type-strict{
    background: #EC7F07 url("~@/assets/images/dash-ring.png") no-repeat;
  }

  .type-active{
    box-sizing: border-box;
    position: relative;
    border: #fff 1px dashed;
  }

  .type-active  .check{
    display: block;
    position: absolute;
    top: 5px;
    right: 5px;
    color: #fff !important;
  }

  .el-tab-pane{
    padding-left: 10px;
    padding-right: 20px;
  }

</style>
